package com.tjcd.project.library_base.base.network;

import android.os.Build;
import android.text.TextUtils;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonParser;
import com.tjcd.project.library_base.common.basicInfor.SugarSpConst;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * @Author jiangKunKun
 * @CreateDate 2021/7/7
 * @Description 网络拦截器
 * @SpittingGrooves
 */
public class NetInterceptor implements Interceptor {
    private String mJsonstr;
    private StringBuilder mBody = new StringBuilder();

    @Override
    public Response intercept(Chain chain) throws IOException{
        if (!antiCapture()){
            ToastUtils.showLong("禁止开代理");
            return null;
        }
        if (!NetworkUtils.isConnected()) {
            ToastUtils.showLong("网路异常");
            return null;
        }
        // 拦截请求，获取到该次请求的request
        Request request = chain.request().newBuilder()
                // 安卓系统版本
                .addHeader("device-systemName", DeviceUtils.getSDKVersionName())
                // 系统版本对应的版本号
                .addHeader("device-systemCode", DeviceUtils.getSDKVersionCode() + "")
                // 安卓id
                .addHeader("device-systemAndroidID", DeviceUtils.getAndroidID())
                // 制造商 如 Xiaomi
                .addHeader("device-systemManufacturer", DeviceUtils.getManufacturer())
                // 手机型号 如 MI9
                .addHeader("device-systemVersion", DeviceUtils.getModel())
                // 设备唯一id
                .addHeader("device-systemOnlyId", DeviceUtils.getUniqueDeviceId())
                // app 包名
                .addHeader("app-packageName", AppUtils.getAppPackageName())
                // app 版本号
                .addHeader("app-version", AppUtils.getAppVersionName())
                // app code码
                .addHeader("app-versionName", AppUtils.getAppVersionCode() + "")
                // 来源
                .addHeader("source", "APP_Android")
                // token
                .addHeader("token", TextUtils.isEmpty(SugarSpConst.getToken()) ? "" : SugarSpConst.getToken())
                .build();


        // 执行本次网络请求操作，返回response信息
        Response response = chain.proceed(request);
        mJsonstr = response.body().string();
        // 对post进行解密
        if ("POST".equals(request.method())) {
//            try {
//                // 对数据进行解密
//                String postJsonStr = new JsonParser().parse(mJsonstr).getAsJsonObject().get("rsa").getAsString();
//                mJsonstr = RSAUtil.decrypt(postJsonStr, RSAUtil.PRIVATE_KEY);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

            // 清空 StringBuilder 里的值
            if (0 < mBody.length()){
                mBody.delete(0, mBody.length());
            }

            Buffer buffer = new Buffer();
            try {
                request.body().writeTo(buffer);
                //编码设为UTF-8
                Charset charset = StandardCharsets.UTF_8;
                MediaType contentType = request.body().contentType();
                if (contentType != null) {
                    charset = contentType.charset(StandardCharsets.UTF_8);
                }
                //拿到request
                String requestString = buffer.readString(charset);
                mBody.append(requestString);
            } catch (IOException e) {
                e.printStackTrace();
            }

            LogUtils.e("请求方式: " + request.method() + "\nHttps Code = " + response.code() + "\n请求连接:" + request.url() +
                    "\n请求头:\n" + request.headers() + "\n请求参数:\n" + mBody.toString() + "\n请求结果:\n" + mJsonstr);
        } else { // 其他请求直接返回
            LogUtils.e("请求方式: " + request.method() + "\nHttps Code = " + response.code() + "\n请求连接:" + request.url() +
                    "\n请求头:\n" + request.headers() + "\n请求结果:\n" + mJsonstr);
        }

        // 根据 Code 码 判断 Token 失效
        try {
            int code = new JsonParser().parse(mJsonstr).getAsJsonObject().get("code").getAsInt();
            if (code == 401) {
                if (ObjectUtils.isNotEmpty(SugarSpConst.getToken())) {
                    ToastUtils.showLong("token失效，请重新登录");
                    // 清除缓存

                    // EventBus 发送通知

//                    NetManager.resetRetrofit();
                }
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.newBuilder()
                .body(ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), mJsonstr))
                .build();
    }

    /**
     * 反抓包
     */
    private boolean antiCapture(){
        final boolean iSICSORLATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
        String proxyAddress;
        if (iSICSORLATER) {
            proxyAddress = System.getProperty("http.proxyHost");
            String portStr = System.getProperty("http.proxyPort");
            if (TextUtils.isEmpty(proxyAddress) && TextUtils.isEmpty(portStr)){
                return true;
            }
        }
        return false;
    }
}
